//
//  NSAttributedString+safe.m
//  ItGirls
//
//  Created by WuShiHai on 26/09/2016.
//  Copyright © 2016 微盟. All rights reserved.
//

#import "NSAttributedString+LBSafe.h"
#import <objc/runtime.h>

static IMP WYMIReplaceMethodWithBlock(Class c, SEL origSEL, id block) {
    NSCParameterAssert(block);
    
    // get original method
    Method origMethod = class_getInstanceMethod(c, origSEL);
    NSCParameterAssert(origMethod);
    
    // convert block to IMP trampoline and replace method implementation
    IMP newIMP = imp_implementationWithBlock(block);
    
    // Try adding the method if not yet in the current class
    if (!class_addMethod(c, origSEL, newIMP, method_getTypeEncoding(origMethod))) {
        return method_setImplementation(origMethod, newIMP);
    }else {
        return method_getImplementation(origMethod);
    }
}


@implementation NSAttributedString (LBSafe)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self replaceMethod];
    });
}

+ (void)replaceMethod {
    __block IMP originalInitWithStringIMP = WYMIReplaceMethodWithBlock(NSClassFromString(@"NSConcreteAttributedString"), @selector(initWithString:), (id)^(id object,NSString *aString) {
        
        if (aString == nil) {
            aString = @"";
        }
        
        id obj = ((id (*)(id, SEL,NSString *))originalInitWithStringIMP)(object, @selector(initWithString:),aString);
        
        return obj;
    });
}
@end
